// 自己根据业务需要封装使用高德地图的构造函数UseAmap
function UseAmap(opts){
  // 构造函数需要的参数
  this.dom = opts.dom;                        // 地图主体DOM
  this.list = opts.list;                      // 一开始需要绑定事件的DOM列表
  this.unbindList = [];                       // init时复制到这个数组中，等待绑定事件
  this.uncreateMarkerList = [];               // init时复制到这个数组中，等待创建Marker
  this.centerX = opts.data.centerX || 0;           // 地图初始化时的centerX和Y和放大等级
  this.centerY = opts.data.centerY || 0;           
  this.setMapZooom = opts.data.setMapZooom || 13;    
  this.move = null;                           // 局部的interval事件名称
  this.markers = {};                          // Marker存放处
  this.map = new AMap.Map(this.dom);          // 高德地图实例化 
  this.init();                                // 初始化
  this.createMarker();                        // Marker实例化
  this.bindDOM();                             // DOM绑定
}

// 初始化
UseAmap.prototype.init = function(){
  // this.R = ($(this.dom).width()*$(this.dom).width()) + ($(this.dom).height()*$(this.dom).height())
  // 复制两个list
  for(var i = 0 ; i < this.list.length ; i ++){
    this.unbindList[this.unbindList.length] = this.list[i]; 
  }
  for(var i = 0 ; i < this.list.length ; i ++){
    this.uncreateMarkerList[this.uncreateMarkerList.length] = this.list[i]; 
  }
  // 地图中心，放大等级，组件
  this.map.setZoom(this.setMapZooom);
  this.map.setCenter([this.centerX,this.centerY]);

  var self = this;
  AMap.plugin(['AMap.ToolBar','AMap.Scale','AMap.OverView'],
    function(){
        self.map.addControl(new AMap.ToolBar());

        self.map.addControl(new AMap.Scale());

        // self.map.addControl(new AMap.OverView({isOpen:true}));
  });
}



// Marker
UseAmap.prototype.createMarker = function(){
  // uncreateMarkerList:还没创建Marker的列表
  for(var i = 0 , j = 0; i < this.uncreateMarkerList.length ;  j++){
    // 用DOM的id名来命名。经纬度在DOM上的自定义属性
    var name = this.uncreateMarkerList[i].getAttribute("data-business_name");
    this.markers[this.uncreateMarkerList[i].getAttribute("data-business_id") + "_" + this.uncreateMarkerList[i].getAttribute("data-category_id")] = new AMap.Marker({
        position: [this.uncreateMarkerList[i].getAttribute("data-lng"),this.uncreateMarkerList[i].getAttribute("data-lat")],
        draggable: false,
        cursor: 'auto',
        // Marker外观，可用DOM
        content:"<div style='position:relative' class='newMarker' id='newMarker_"+this.uncreateMarkerList[i].getAttribute("data-business_id") + "_" + this.uncreateMarkerList[i].getAttribute("data-category_id")+"'>"
                  +"<span data-name='"+this.uncreateMarkerList[i].getAttribute("data-business_name")+"' class='markers-name hide' style='padding:0 0 0 10px;width:140px;text-align:center;font-size: 12px;line-height: 24px;border-radius:14px;border:1px solid #aaa;position:absolute;top:2px;left:10px;background-color:#fff;box-shadow: 1px 1px 3px rgba(0,0,0,0.18);'><i>"+this.uncreateMarkerList[i].getAttribute("data-business_name")+"</i></span>"
                  +"<div class='marker-bg' style='width:27px; height:36px; position: absolute;top: 0px; left: 0px;background-image:url(/gosport/index/images/location-blue.png);'>"
                    +"<span style='width:100%;text-align:center;font-size: 12px;line-height: 28px;'>"+(j+1)+"</span>"
                  +"</div>"
                +"</div>"
      });
    // 配置到map上，列表shift，循环
    this.markers[this.uncreateMarkerList[i].getAttribute("data-business_id") + "_" + this.uncreateMarkerList[i].getAttribute("data-category_id")].setMap(this.map);
    this.uncreateMarkerList.shift();
  }
}

// 绑定
UseAmap.prototype.bindDOM = function(){
  // unbindList:还没绑定的列表
  for(var i = 0 ; i < this.unbindList.length ; ){
    // 传入dom和"mouseover"
    this.bindMoveFn(this.unbindList[i],"mouseover");
    this.bindOutFn(this.unbindList[i],"mouseleave");
    // 列表shift，循环
    this.unbindList.shift();
  }
}
UseAmap.prototype.bindOutFn = function(dom,str){
  $(dom).on(str,move);
  function move(){
    $(this).attr("data-mouse","leave");
  }
}
// 绑定move函数
UseAmap.prototype.bindMoveFn = function(dom,str){
  var self = this;
  // 把传入的DOM绑定move函数
  $(dom).on(str,move);

  function move(){
    if($(this).attr("data-mouse") == "over") return false;
    $(this).attr("data-mouse","over");
    self.changeIcon($("#newMarker_"+this.getAttribute("data-business_id") + "_" + this.getAttribute("data-category_id") )[0])
    // 获得当前地图的经纬度
    self.centerX = self.map.getCenter().lng;
    self.centerY = self.map.getCenter().lat;

    // DOM没有经纬度就return
    if(!this.getAttribute("data-lng")) return false;
    if(!this.getAttribute("data-lat")) return false;

    // 计算当前经纬度与DOM上存的经纬度之间的距离（近似值，单位米）
    // a，b为两点纬度，c是两点经度差
    // var c = Math.abs(self.centerX - this.getAttribute("data-lng"));
    // var a = this.getAttribute("data-lat");
    // var b = self.centerY;
    // var d = distanceTowPoint(a,b,c);

    // if( d <= 10000){
      self.setMapZooom = 13;  // 距离小于10000米 放大等级设置为13
    // }else if(d <= 100000){
    //   self.setMapZooom = 12;  // 距离于10000米至100000米 放大等级设置为12
    // }else if(d <= 1000000){
    //   self.setMapZooom = 6;
    // }else if(d <= 10000000){
    //   self.setMapZooom = 3;
    // }else if(d <= 100000000){
    //   self.setMapZooom = 1;
    // }else{
    //   self.setMapZooom = 1;
    // }
    self.map.setZoom(self.setMapZooom);

    self.map.setCenter([this.getAttribute("data-lng"),this.getAttribute("data-lat")]);

    self.markers[this.getAttribute("data-business_id") + "_" + this.getAttribute("data-category_id")].setAnimation("AMAP_ANIMATION_DROP");
    

  //   clearInterval(self.move); // 先清interval

  //   // 计算距离，步长
  //   var distanceX = this.getAttribute("data-lng") - self.centerX;
  //   var distanceY = this.getAttribute("data-lat") - self.centerY;
  //   var stepX = distanceX / 10;
  //   var stepY = distanceY / 10;
  //   var that = this;

  //   // interval开始（动画效果）每100ms增加步长并移动地图中心
  //   self.move = setInterval(function(){
  //     self.centerX += stepX; 
  //     self.centerY += stepY; 
  //     self.map.setCenter([self.centerX,self.centerY]);
     
  //     // 停止判断，并执行动画，地图放大等级至13
  //     if(Math.abs(self.centerX - that.getAttribute("data-lng")) <= 0.00001 && Math.abs(self.centerY - that.getAttribute("data-lat")) <= 0.00001){
  //       clearInterval(self.move);
  //       self.markers[that.getAttribute("data-business_id") + "_" + that.getAttribute("data-category_id")].setAnimation("AMAP_ANIMATION_DROP");
        
  //       // self.setMapZooom = 13;
  //       // self.map.setZoom(self.setMapZooom);
  //     }
  //   },100);  
  }


}

// 距离计算，a，b为两点纬度差，c是两点经度差，R是地球半径评价值
function distanceTowPoint(a,b,c){
  var R = 6371393;
  var PI = Math.PI;
  var C = Math.cos(a * PI / 180) * Math.cos(b * PI / 180)*Math.cos(c * PI / 180) + Math.sin(a * PI / 180) * Math.sin(b * PI /180 );
  var distance = R * Math.acos(C);

  return distance;
}
UseAmap.prototype.changeIcon = changeIcon;
function changeIcon(dom){
  $(".newMarker .marker-bg").each(function(index){
    $(this).find("span").css("color","inherit");
    $(this).css({"background-image":"url(/gosport/index/images/location-blue.png)"}).parents(".amap-marker").css("z-index","100");
  });
  $(".newMarker .markers-name").addClass("hide");
  $(dom).find(".marker-bg").css({"background-image":"url(/gosport/index/images/location-red.png)"}).parents(".amap-marker").css("z-index","101");
  $(dom).find(".marker-bg span").css({"color":"#ec622f"});
  $(dom).find(".markers-name").removeClass("hide");
  $(dom).find(".markers-name").css({"width": this.markerNameHandle($(dom).find("i").text()).width + "px"});
  $(dom).find("i").text(this.markerNameHandle($(dom).find(".markers-name").attr("data-name")).name);
}

UseAmap.prototype.markerNameHandle = function(str){
  var width = null;
  if(!str) return false;
  if(str.length > 10){
    str = str.substr(0,3) + "..." + str.substr(str.length - 1 - 6 , 6 );
    width = 10 * 14 ;
  }else{
    width = str.length * 15 ;
  }

  return {name:str,width:width}
}